import JSEncrypt from 'jsencrypt'

/**
 * 按指定长度分段字符串
 * @param str 传入的字符串(非空)
 * @param num 指定长度(正整数)
 * @returns Array(字符串数组)
 */
 function fixedLengthFormatString(str,num){
  if(str == null || str == undefined) return '';
  if(!(/^[0-9]*[1-9][0-9]*$/.test(num))) str += '';
  var array = new Array();
  var len = str.length;
  for(var i=0;i<(len/num);i++){
    if((i+1)*num > len){
    array.push(str.substring(i*num,len));
}else{
    array.push(str.substring(i*num,(i+1)*num));
}
  }
  return array;
}

/**
 * 默认通用请求
 **/

const pk = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDl/jxbMsO1IYZJlihKsMQKbN6XzT3fiKBuaxK7yp/7r1YdW+SV3rDPrAUQoQDcW7tdYOuCKbKmYZFNKntfW2z8H9DppbZmquLZv37WlF5EvJ9nHzYQzeC9Nvr7MIHbbtVpAOZZPH/6AGyPAoed+UxENlpp03fCmq4z68hg0GaahQIDAQAB"

// 加密（origin：原始text，key：公钥）
export const encrypt = (origin) => {
  if(typeof origin !== 'string') origin = JSON.stringify(origin);
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(pk)
  // 分段加密， 默认按 20 length 分段加密
  const originArray = fixedLengthFormatString(origin, 20);
  let encryptData = [];
  originArray.forEach(el => {
    encryptData.push(encryptor.encrypt(el))
  })
  console.log('参数json: ', origin);
  return encryptData;
}


